/*
 * Copyright 2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mx.ymate.serv;

import com.mx.ymate.serv.impl.DefaultMxServConfig;
import com.mx.ymate.serv.impl.TcpClient;
import com.mx.ymate.serv.impl.TcpServer;
import com.mx.ymate.serv.util.TcpClientStore;
import com.mx.ymate.serv.util.TcpServerStore;
import net.ymate.platform.core.*;
import net.ymate.platform.core.module.IModule;
import net.ymate.platform.core.module.IModuleConfigurer;
import net.ymate.platform.core.module.impl.DefaultModuleConfigurer;
import net.ymate.platform.serv.nio.INioSession;
import net.ymate.platform.serv.nio.server.NioSessionManager;
import net.ymate.platform.serv.nio.server.NioSessionWrapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;

import static com.mx.ymate.serv.IMxServConfig.SERVER_CLIENT_CLIENT;
import static com.mx.ymate.serv.IMxServConfig.SERVER_CLIENT_SERVER;

/**
 * MxServ generated By ModuleMojo on 2022/07/07 14:10
 *
 * @author YMP (https://www.ymate.net/)
 */
public final class MxServ implements IModule, IMxServ {

    private static final Log LOG = LogFactory.getLog(MxServ.class);

    private static volatile IMxServ instance;

    private IApplication owner;

    private IMxServConfig config;

    private TcpServer tcpServer;
    private TcpClient tcpClient;

    NioSessionManager<NioSessionWrapper, Object> sessionManager;

    private boolean initialized;

    public static IMxServ get() {
        IMxServ inst = instance;
        if (inst == null) {
            synchronized (MxServ.class) {
                inst = instance;
                if (inst == null) {
                    instance = inst = YMP.get().getModuleManager().getModule(MxServ.class);
                }
            }
        }
        return inst;
    }

    public MxServ() {
    }

    public MxServ(IMxServConfig config) {
        this.config = config;
    }

    @Override
    public String getName() {
        return MODULE_NAME;
    }

    @Override
    public void initialize(IApplication owner) throws Exception {
        if (!initialized) {
            //
            YMP.showVersion("Initializing mx-ymate-serv-mxserv-${version}", new Version(1, 0, 0, MxServ.class, Version.VersionType.Alpha));
            //
            this.owner = owner;
            if (config == null) {
                IApplicationConfigureFactory configureFactory = owner.getConfigureFactory();
                if (configureFactory != null) {
                    IApplicationConfigurer configurer = configureFactory.getConfigurer();
                    IModuleConfigurer moduleConfigurer = configurer == null ? null : configurer.getModuleConfigurer(MODULE_NAME);
                    if (moduleConfigurer != null) {
                        config = DefaultMxServConfig.create(moduleConfigurer);
                    } else {
                        config = DefaultMxServConfig.create(DefaultModuleConfigurer.createEmpty(MODULE_NAME));
                    }
                }
                if (config == null) {
                    config = DefaultMxServConfig.defaultConfig();
                }
            }
            if (!config.isInitialized()) {
                config.initialize(this);
            }
            if (config.isEnabled()) {
                if (SERVER_CLIENT_SERVER.equals(config.getClient())) {
                    tcpServer = new TcpServer(config);
                    sessionManager = tcpServer.run();
                } else if (SERVER_CLIENT_CLIENT.equals(config.getClient())) {
                    tcpClient = new TcpClient(config);
                    tcpClient.run();
                } else {
                    tcpServer = new TcpServer(config);
                    tcpClient = new TcpClient(config);
                    sessionManager = tcpServer.run();
                    tcpClient.run();
                }
            }
            initialized = true;
        }
    }

    @Override
    public boolean isInitialized() {
        return initialized;
    }

    @Override
    public void close() throws Exception {
        if (initialized) {
            initialized = false;
            //
            if (config.isEnabled()) {
                if (SERVER_CLIENT_SERVER.equals(config.getClient())) {
                    if (tcpServer != null) {
                        tcpServer.stop();
                    }
                } else if (SERVER_CLIENT_CLIENT.equals(config.getClient())) {
                    if (tcpClient != null) {
                        tcpClient.stop();
                    }
                } else {
                    if (tcpClient != null && tcpServer != null) {
                        tcpServer.stop();
                        tcpClient.stop();
                    }

                }
            }
            //
            config = null;
            owner = null;
        }
    }

    @Override
    public IApplication getOwner() {
        return owner;
    }

    @Override
    public IMxServConfig getConfig() {
        return config;
    }

    @Override
    public boolean stc(String key, Object message) throws IOException {
        NioSessionWrapper nioSessionWrapper = TcpServerStore.getSession(key);
        if (nioSessionWrapper != null) {
            return sessionManager.sendTo(nioSessionWrapper.getId(), message);
        }
        return false;
    }

    @Override
    public void cts(String key, Object message) throws IOException {
        INioSession nioClient = TcpClientStore.getClient(key);
        if (nioClient != null) {
            nioClient.send(message);
        }
    }
}
